extends Node2D

var fall_speed := 50.0      # 基础下落速度
var sway_amplitude := 80.0  # 水平摆动幅度
var sway_frequency := 2.0   # 摆动频率
var rotation_speed := 1.5   # 旋转速度
var tween

func _ready():
	# 随机化参数使每片叶子不同
	fall_speed = rand_range(40, 60)
	sway_amplitude = rand_range(60, 100)
	sway_frequency = rand_range(1.5, 2.5)
	rotation_speed = rand_range(-2.0, 2.0)
	
	
	# 创建飘落动画
	var start_pos := position
	var duration := rand_range(3.0, 5.0)
	
	# 创建Tween动画
	tween = Tween.new()
	add_child(tween)
	
	# 垂直下落
	tween.interpolate_property(self, "position:y",
		position.y, position.y + 1000, duration,
		Tween.TRANS_LINEAR, Tween.EASE_IN)
	
	# 水平摆动（贝塞尔曲线实现自然摆动）
	var sway_points := PoolVector2Array()
	for i in 5:
		var x_offset = sway_amplitude * pow(-1, i)
		sway_points.append(Vector2(x_offset, i * 200))
	
	tween.interpolate_method(self, "apply_sway",
		sway_points, [], duration,
		Tween.TRANS_SINE, Tween.EASE_IN_OUT)
	
	# 旋转动画
	tween.interpolate_property(self, "rotation",
		0, rotation_speed * PI, duration,
		Tween.TRANS_QUAD, Tween.EASE_IN_OUT)
	
	tween.start()
	
	# 动画完成后自动移除
	yield(tween, "tween_completed")
	queue_free()


func apply_sway(points: PoolVector2Array):
	var progress = 1.0 - tween.get_runtime() / tween.get_total_time()
	var current_index = int(progress * (points.size() - 1))
	position.x = points[current_index].x
